package com.gdcp.controller.backend;

import com.gdcp.beans.Category;
import com.gdcp.beans.Role;
import com.gdcp.beans.Shop;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.CategoryService;
import com.gdcp.service.ShopService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@RolesAllowed({"ROLE_SHOP_ADMIN","ROLE_ADMIN"})
@Controller
@RequestMapping("/render/categoryManager")
public class CategoryController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    CategoryService categoryService;
    @Autowired
    CommonCode commonCode;
    @Autowired
    ShopService shopService;

    //@PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber, String sortName, String sortOrder){
        Map<String,Object> model=commonCode.getList(pageSize,pageNumber,sortName,sortOrder);
        //通过
        User user= (User) RequestHolder.getSession("user");
        for (Role role: user.getRoles()){
            //System.out.println(role.getName());
            if (role.getName().equals("ROLE_ADMIN")){
                return categoryService.findAll(model);
            }
        }
        model.put("shop_id",user.getShop_id());
        if (user.getShop_id()!=0){
            return categoryService.findPageBreakByCondition(model, user.getShop_id());
        }

        return responseModel.setModel(false,"信息错误");
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(Category category){
        //就算是超级管理员也要验证该分类的店铺是否存在
        //验证该分类是否存在，再验证该分类的店铺id是否和现在的一致
        User user= (User) RequestHolder.getSession("user");
        if (user.getShop_id()!=0){
            Shop shop=shopService.getInformation(category.getShop_id());
            if (shop==null){
                return responseModel.setModel(false,"修改失败，该店铺id为"+category.getShop_id()+"不存在");
            }
        }
        return categoryService.updateByCategory(category);
    }

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> search(String searchText){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> model=new HashMap<>();

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            model.put("name", jsonOne.getString("name"));
            model.put("parent_id", jsonOne.getString("parent_id"));
            model.put("id", jsonOne.getString("id"));
        }

        User user= (User) RequestHolder.getSession("user");
        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                return categoryService.searchInformation(model);
            }
        }

        model.put("shop_id",user.getShop_id());
        if (user.getShop_id()==0){
            return responseModel.setModel(false,"信息错误");
        }
        return categoryService.searchInformationByShopId(model, user.getShop_id());
    }

    @RequestMapping(value = "/queryByAll",method = RequestMethod.GET)
    public String queryByAll(){
        HttpServletRequest request=RequestHolder.getRequest();
        User user= (User) RequestHolder.getSession("user");
        for (Role role: user.getRoles()){
            if (role.getName().equals("ROLE_ADMIN")){
                List<Category> category = categoryService.queryByAll();
                request.setAttribute("categories",category);
            }else if (role.getName().equals("ROLE_SHOP_ADMIN")){
                List<Category> category = categoryService.queryByParentId(3);
                List<Category> categories=new ArrayList<>();
                for (Category category1:category){
                    if (category1.getShop_id().equals(0)){
                        categories.add(category1);
                    }
                }

                request.setAttribute("categories",categories);
            }
        }

        return "admin/categoryManager";
    }

    @PostMapping("/get/{id}")
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        Category category= categoryService.getInformation(id);
        if (category!=null){
            return responseModel.setModel(true,category);
        }

        return responseModel.setModel(false,"获取失败");
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }

        return categoryService.removeByPrimaryKey(ids);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(Category category){
        return categoryService.insert(category);
    }
}
